import React, { useState, useEffect } from 'react';
import { Row, Col, Spin } from 'antd';
import axios from 'axios';
import Header from './header';
import PlatformCard from '../../component/portal/platformCard';

// 类型定义
interface MainCard {
  id: number;
  title: string;
  sortOrder: number;
}

interface SubCard {
  id: number;
  mainCardId: number;
  text: string;
  link: string;
  sortOrder: number;
}

// 样式定义
const contentStyle: React.CSSProperties = {
  position: 'absolute',
  left: '60px',
  width: 'calc(100% - 120px)',
  padding: '16px 0'
};

const gridStyle: React.CSSProperties = {
  width: '50%',
  textAlign: 'center',
  height: '50px',
  padding: '15px',
  cursor: 'pointer'
};

export default function Portal() {
  const [cardConfigs, setCardConfigs] = useState<Array<{
    title: string;
    gridItems: Array<{ text: string; link: string }>;
  }>>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  useEffect(() => {
    const fetchData = async () => {
      try {
        // 获取主卡片[6,7](@ref)
        const mainRes = await axios.get('http://localhost:9090/api/cards/main/page');
        const mainCards: MainCard[] = mainRes.data.records.sort((a: any, b: any) => a.sortOrder - b.sortOrder);

        // 并行获取子卡片[3,8](@ref)
        const subPromises = mainCards.map(mainCard =>
          axios.get(`http://localhost:9090/api/cards/sub/by-main/${mainCard.id}`)
        );

        const subResponses = await Promise.all(subPromises);
        
        // 数据整合[5](@ref)
        const mergedData = mainCards.map((mainCard, index) => ({
          title: mainCard.title,
          gridItems: subResponses[index].data
            .sort((a: SubCard, b: SubCard) => a.sortOrder - b.sortOrder)
            .map((sub: SubCard) => ({
              text: sub.text,
              link: sub.link
            }))
        }));

        setCardConfigs(mergedData);
        setLoading(false);
      } catch (err) {
        setError('数据加载失败，请稍后重试');
        setLoading(false);
      }
    };

    fetchData();
  }, []);

  if (loading) return <Spin size="large" style={{ display: 'block', margin: '20% auto' }} />;
  if (error) return <div style={{ color: 'red', textAlign: 'center' }}>{error}</div>;

  return (
    <>
      <Header />
      <div style={contentStyle}>
        <Row gutter={[32, 32]} justify="center">
          {cardConfigs.map((config, index) => (
            <Col key={index} xs={24} sm={12} md={8} lg={8} xl={10}>
              <PlatformCard
                title={config.title}
                gridItems={config.gridItems}
                gridStyle={gridStyle}
                style={{
                  height: '207px',
                  marginBottom: '16px'
                }}
              />
            </Col>
          ))}
        </Row>
      </div>
    </>
  );
}
